<template>
	<view class="register-page">
		<!-- Logo区域 -->
		<view class="logo-section">
			<view class="logo-container">
				<image src="/static/images/logo.png" class="logo-image" mode="aspectFit" />
			</view>
			<text class="app-title">链智Quant AI</text>
		</view>

		<!-- 表单区域 -->
		<view class="form-section">
			<!-- 用户名输入 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/phone.png" class="input-icon" />
					<input v-model="formData.username" class="input-field" placeholder="请输入邮箱地址" />
				</view>
			</view>

			<!-- 验证码输入 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/safety.png" class="input-icon" />
					<input v-model="formData.captcha" class="input-field" placeholder="请输入邮箱验证码" maxlength="6" />
					<view class="sms-btn" @click="sendSmsCode" :class="{disabled: isSending || countdown > 0}">
						<text class="sms-btn-text">{{ countdown > 0 ? `${countdown}s后重发` : '获取验证码' }}</text>
					</view>
				</view>
			</view>

			<!-- 设置密码 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/lock.png" class="input-icon" />
					<input v-model="formData.password" class="input-field" placeholder="设置密码" :password="true" />
				</view>
			</view>

			<!-- 再次设置密码 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/lock.png" class="input-icon" />
					<input v-model="formData.confirmPassword" class="input-field" placeholder="再次设置密码"
						:password="true" />
				</view>
			</view>

			<!-- 邀请码输入 -->
			<view class="input-group">
				<view class="input-container">
					<image src="/static/images/login/safety.png" class="input-icon" />
					<input v-model="formData.inviteCode" class="input-field" placeholder="请输入邀请码（可选）" />
				</view>
			</view>

			<!-- 协议勾选 -->
			<view class="agreement-section">
				<view class="checkbox-container" @click="toggleAgreement">
					<view class="checkbox" :class="{ checked: isAgreed }">
						<text v-if="isAgreed" class="check-icon">✓</text>
					</view>
					<text class="agreement-text">我已阅读并同意</text>
					<text class="link-text" @click.stop="goToUserManual">《用户手册》</text>
					<text class="agreement-text">和</text>
					<text class="link-text" @click.stop="goToPrivacyPolicy">《隐私政策》</text>
				</view>
			</view>

			<!-- 注册按钮 -->
			<view class="register-btn" :class="{ disabled: !canRegister }" @click="handleRegister">
				<text class="register-btn-text">注册</text>
			</view>

			<!-- 底部链接 -->
			<view class="bottom-links">
				<view class="link-item">
					<text class="link-prefix">有账户？</text>
					<text class="link-text primary" @click="goToLogin">直接登录</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getEmailCaptcha,
		register
	} from '@/api/auth'
	import { checkCaptchaThrottle } from '@/utils/captcha-throttle'

	export default {
		name: 'Register',
		data() {
			return {
				loading: false,
				formData: {
					username: '',
					captcha: '',
					password: '',
					confirmPassword: '',
					inviteCode: '',
				},
				clientId: '',
				isAgreed: false,
				countdown: 0, // 倒计时秒数
				isSending: false, // 是否正在发送验证码
				timer: null, // 倒计时定时器
				lastClickTime: 0, // 上次点击时间，用于防抖
			}
		},

		computed: {
			canRegister() {
				return (
					this.formData.username &&
					this.formData.captcha &&
					this.formData.password &&
					this.formData.confirmPassword &&
					this.isAgreed &&
					!this.loading
				)
			},
		},

		onLoad(options) {
			if (options.inviteCode) {
				this.formData.inviteCode = options.inviteCode
			}
		uni.getPushClientId({
			success: (res) => {
				console.log('获取Push客户端ID成功:', res)
				this.clientId = res.cid
				console.log('clientId:', this.clientId)
			},
			fail: (err) => {
				console.error('获取Push客户端ID失败:', err)
				// 获取失败时使用设备唯一标识作为备选
				try {
					const systemInfo = uni.getSystemInfoSync()
					this.clientId = systemInfo.deviceId || systemInfo.system || 'unknown'
				} catch(e) {
					this.clientId = 'fallback_' + Date.now()
				}
			}
		})
		},

		mounted() {
			// 页面加载完成
		},

		beforeDestroy() {
			// 清理定时器
			if (this.timer) {
				clearInterval(this.timer)
			}
		},

		methods: {
			// 切换协议同意状态
			toggleAgreement() {
				this.isAgreed = !this.isAgreed
			},

			// 发送邮箱验证码
			sendSmsCode() {
				// 判断是否可以发送
				if (this.isSending || this.countdown > 0) return

				// 验证邮箱
				if (!this.formData.username) {
					uni.showToast({
						title: '请输入邮箱地址',
						icon: 'none',
					})
					return
				}

				// 验证邮箱格式
				const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
				if (!emailReg.test(this.formData.username)) {
					uni.showToast({
						title: '请输入正确的邮箱地址',
						icon: 'none',
					})
					return
				}

				// 防抖检查：1秒内最多4个请求
				const throttleCheck = checkCaptchaThrottle()
				if (!throttleCheck.canSend) {
					uni.showToast({
						title: throttleCheck.message,
						icon: 'none',
					})
					return
				}

				this.isSending = true

				// 调用发送邮箱验证码接口
				getEmailCaptcha(this.formData.username)
					.then(response => {
						this.isSending = false
						if (response.code === 200) {
							uni.showToast({
								title: '验证码已发送',
								icon: 'none',
							})
							// 开始倒计时
							this.startCountdown()
						} else {
							uni.showToast({
								title: response.message || '发送失败',
								icon: 'none',
							})
						}
					})
					.catch(error => {
						this.isSending = false
						uni.showToast({
							title: error.message || '发送失败',
							icon: 'none',
						})
					})
			},

			// 开始倒计时
			startCountdown() {
				this.countdown = 60
				this.timer = setInterval(() => {
					this.countdown--
					if (this.countdown <= 0) {
						clearInterval(this.timer)
						this.timer = null
					}
				}, 1000)
			},

			// 处理注册
			handleRegister() {
				if (!this.canRegister) return

				// 防抖检查：500ms内不允许重复点击
				const now = Date.now()
				if (now - this.lastClickTime < 500) {
					return
				}
				this.lastClickTime = now

				// 验证邮箱
				if (!this.formData.username) {
					uni.showToast({
						title: '请输入邮箱地址',
						icon: 'none',
					})
					return
				}

				// 验证验证码
				if (!this.formData.captcha) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
					})
					return
				}

				// 验证密码（8-20位）
				if (!this.formData.password || this.formData.password.length < 8 || this.formData.password.length > 20) {
					uni.showToast({
						title: '密码必须由8-20位字符组成',
						icon: 'none',
					})
					return
				}

				// 验证确认密码
				if (this.formData.password !== this.formData.confirmPassword) {
					uni.showToast({
						title: '两次密码输入不一致',
						icon: 'none',
					})
					return
				}

				this.loading = true
				
				// 确保clientId存在
				if (!this.clientId) {
					console.warn('clientId未获取到，使用临时ID')
					this.clientId = 'temp_' + Date.now()
				}

				// 构建注册参数 - 确保所有必需参数都传递
				const registerData = {
					username: this.formData.username,
					password: this.formData.password,
					captcha: this.formData.captcha,
					inviteCode: this.formData.inviteCode || '', // 可选参数
					uniClientId: this.clientId,
					loginType: 1 // 1: 邮箱注册
				}
				
				console.log('注册参数:', registerData)

				// 调用注册API
				register(registerData)
					.then((res) => {
						this.loading = false
						console.log(res);
						const {
							code,
							message
						} = res
						if (code === 200) {
							uni.showToast({
								title: '注册成功！',
								icon: 'none',
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 1500)
						} else {
							uni.showToast({
								title: message,
								icon: "none"
							})
						}
					})
					.catch(error => {
						this.loading = false
						// 清空验证码
						this.formData.captcha = ''
						const errMsg = typeof error === 'string' ? error : (error?.message || '注册失败')
						uni.showToast({
							title: errMsg,
							icon: 'none',
						})
					})
			},

			// 跳转到用户手册
			goToUserManual() {
				uni.navigateTo({
					url: '/subPages/auth/user-manual'
				})
			},

			// 跳转到隐私政策
			goToPrivacyPolicy() {
				uni.navigateTo({
					url: '/subPages/auth/privacy'
				})
			},

			// 跳转到登录页面
			goToLogin() {
				uni.navigateTo({
					url: '/subPages/auth/login'
				})
			},
		},
	}
</script>

<style lang="scss" scoped>
	.register-page {
		display: flex;
		flex-direction: column;
		align-items: center;
		min-height: 100vh;
		padding: 0;
		background: url('/static/images/login/login-bg.png') no-repeat center center;
		background-size: cover;
	}

	// Logo区域
	.logo-section {
		margin-top: 120rpx;
		margin-bottom: 80rpx;
		text-align: center;

		.logo-container {
			margin-bottom: 32rpx;

			.logo-image {
				width: 140rpx;
				height: 140rpx;
				border-radius: 28rpx;
				box-shadow: 0 8rpx 32rpx rgba(0, 212, 170, 0.25);
			}
		}

		.app-title {
			font-size: 44rpx;
			font-weight: 600;
			color: #333;
			letter-spacing: 2rpx;
		}
	}

	// 表单区域
	.form-section {
		flex: 1;
		width: 100%;
		padding: 0 64rpx;
	}

	// 输入框组
	.input-group {
		margin-bottom: 28rpx;

		.input-container {
			position: relative;
			display: flex;
			align-items: center;
			height: 88rpx;
			padding: 0 32rpx;
			background-color: #fff;
			border-radius: 44rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

			.input-icon {
				width: 32rpx;
				height: 32rpx;
				margin-right: 20rpx;
				opacity: 0.6;
			}

			.input-field {
				flex: 1;
				height: 100%;
				font-size: 28rpx;
				color: #333;
				background: transparent;
				border: none;
				outline: none;

				&::placeholder {
					font-size: 28rpx;
					color: #aaa;
				}
			}

			.sms-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 180rpx;
				height: 60rpx;
				padding: 0 20rpx;
				margin-left: 20rpx;
				cursor: pointer;
				transition: all 0.3s ease;

				&:active {
					opacity: 0.7;
				}

				&.disabled {
					cursor: not-allowed;
				}

				.sms-btn-text {
					font-size: 26rpx;
					font-weight: 500;
					color: #00c299;
					white-space: nowrap;
				}

				&.disabled .sms-btn-text {
					color: #999;
				}
			}
		}
	}

	// 协议区域
	.agreement-section {
		margin-bottom: 40rpx;
		margin-top: 8rpx;

		.checkbox-container {
			display: flex;
			flex-wrap: nowrap;
			align-items: center;

			.checkbox {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 30rpx;
				height: 30rpx;
				margin-right: 12rpx;
				background-color: #fff;
				border: 2rpx solid #00d4aa;
				border-radius: 6rpx;
				transition: all 0.3s ease;

				&.checked {
					background-color: #00d4aa;
				}

				.check-icon {
					font-size: 18rpx;
					font-weight: bold;
					color: #fff;
				}
			}

			.agreement-text {
				margin-right: 4rpx;
				font-size: 24rpx;
				color: #666;
			}

			.link-text {
				margin-right: 4rpx;
				font-size: 24rpx;
				color: #00d4aa;
				text-decoration: underline;
			}
		}
	}

	// 注册按钮
	.register-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 88rpx;
		margin-bottom: 32rpx;
		background-color: #00d4aa;
		border-radius: 44rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 212, 170, 0.35);
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
		}

		&.disabled {
			background-color: #d0d0d0;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		}

		.register-btn-text {
			font-size: 32rpx;
			font-weight: 600;
			color: #fff;
		}
	}

	// 底部链接
	.bottom-links {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16rpx;
		margin-bottom: 20rpx;

		.link-item {
			display: flex;
			align-items: center;
			justify-content: center;

			.link-prefix {
				font-size: 26rpx;
				color: #8892a0;
				margin-right: 8rpx;
			}

			.link-text {
				font-size: 26rpx;
				color: #666;
				transition: color 0.3s ease;

				&.primary {
					color: #00d4aa;
					font-weight: 500;
				}

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
</style>